package Tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class _530_MinimumAbsoluteDifferenceinBST {
    ArrayList<Integer> numbers;
    public int getMinimumDifference(TreeNode root) {
        int min = Integer.MAX_VALUE;
        numbers = new ArrayList<Integer>();
        getNumber(root);
        int[] nums = new int[numbers.size()];
        for (int i = 0; i < numbers.size(); i++) {
            nums[i] = numbers.get(i);
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length-1; i++) {
            int tempSub = nums[i + 1] - nums[i];
            if (min > tempSub) {
                min = tempSub;
            }
        }
        return min;
    }

    public void getNumber(TreeNode node) {
        if (node == null) {
            return;
        }
        numbers.add(node.val);
        getNumber(node.left);
        getNumber(node.right);
    }

    //solution 2:reference solution:use BST's characteristic
    int min = Integer.MAX_VALUE;
    TreeNode prev = null;

    public int getMinimumDifference_1(TreeNode root) {
        if (root == null) {
            return min;
        }

        getMinimumDifference(root.left);
        if (prev != null) {
            min = Math.min(min, root.val - prev.val);
        }
        prev = root;
        getMinimumDifference(root.right);

        return min;

    }
}
